package com.fast.fastenjoy.base.utils;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;

public class JSObjectUtils extends JSONUtils{
	
	public static final String BOOL_REGEX = "^true|false|TRUE|FALSE$";
	
	public static final String DOUBEL_REGEX = "^\\d+|\\d+\\.\\d+$";

	public static final String V_UNDEFINED = "undefined"; 
	
	public static final String A_FUN_REGEX = "^function\\s{0,}\\((.|\\s)+$";
	
	public static final String JS_DATA_NEW_LINE_MARK = "NNewLineN";
	
	public static boolean isAnonymousFun(String fun){
		
		return fun != null && fun.trim().matches(A_FUN_REGEX);
	}
	
	/**
	 * 返回数据，如果为基础数据类型则返回基础数据，如果为javaBean则返回json格式数据
	 * @param data
	 * @return
	 */
	public static String getParamData(Object data){
		
		StringBuffer sb = new StringBuffer();
		
		if(data == null){
			sb.append(V_UNDEFINED);
		}else if(data instanceof Number || data instanceof Boolean){
			sb.append(data);
		}else if(data instanceof String){
			if(isJson(data.toString()) != null){
				sb.append(data);
			}else{
				
				String tempData = String.valueOf(data);
				
				// 避免换行导致js脚本执行错误，替换换行符号
				tempData = tempData.replaceAll("(\\r\\n|\\r|\\n)", JS_DATA_NEW_LINE_MARK);
				
				sb.append("'").append(tempData).append("'");
			}
		}else{
			sb.append(JSONObject.toJSONString(data));
		}
		
		return sb.toString();
	}
	
	public static JSONObject isJson(String data){
		
		try{
			return JSONObject.parseObject(data);
		}catch(Exception e){
		}
		
		return null;
	}
	
	public static boolean isNum(String data){
		
		return data != null && data.matches(DOUBEL_REGEX);
	}
	
	public static boolean isBool(String data){
		
		return data != null && data.matches(BOOL_REGEX);
	}
	
	/**
	 * 获取是否为异步，默认为true
	 * @param asyncStr
	 * @return
	 */
	public static boolean getBoolean(String boolValue, boolean defaultValue){
		
		if(isBool(boolValue)){
			return Boolean.valueOf(boolValue);
		}
		
		return defaultValue;
	}
	
}
